<?php
class User{
	public static $current;

	public static function get_user_list($active = False){
		$sql = "SELECT * FROM user ";
		if ($active){
			$sql .= " WHERE active = TRUE " ;
		}
		$sql .= "ORDER BY idbooster";

		$conn = mysql::$conn;
		$query = $conn->query($sql);
		$users = $query->fetchAll(PDO::FETCH_OBJ);
		foreach($users as &$user){
			$user = new User($user);
		}
		$query->closeCursor();
		return $users;
	}

	public static function get_user_by_id($idbooster){
		$sql = "SELECT * FROM user WHERE idbooster = :idbooster";

		$conn = mysql::$conn;
		$query = $conn->prepare($sql);
		$query->execute(array('idbooster' => $idbooster));

		$res = $query->fetch(PDO::FETCH_OBJ);

		if(!is_object($res)){
			return false;
		}

		return new User($res);
	}

	public static function auth($idbooster,$password){
		$password = md5($password);

		$sql = "SELECT * FROM user WHERE active = TRUE AND idbooster = :idbooster AND password = :pass";

		$conn = mysql::$conn;
		$query = $conn->prepare($sql);
		$query->execute(array('idbooster' => $idbooster, 'pass' => $password));

		$res = $query->fetch(PDO::FETCH_OBJ);

		if(!is_object($res)){
			return false;
		}

		self::$current = new User($res);
	}

	var $data = Array('iduser'	   => "NULL",
					  'idbooster'  => "NULL",
		              'name'       => "NULL",
					  'surname'    => "NULL",
					  'password'   => "NULL",
					  'admin'      => "NULL",
					  'role'       => "NULL",
					  'join_date'  => "NULL",
					  'leave_date' => "NULL",
					  'active'     => "NULL",
					  'comment'    => "NULL",
					  'idpromo'	   => "NULL",				
	);

	function User($user=False){
		if($user){
			foreach($user as $key=>$value){
				if($value == ""){
					$value = "NULL";
				}
				$this->$key = $value;
			}
		}
	}

	function insert(){
		$sql = "INSERT INTO user VALUES ( :iduser,:name,:surname,:idbooster,:password,:admin,:role,:join_date,:leave_date,:active,:comment,:idpromo)";
		$conn = mysql::$conn;
		$query=$conn->prepare($sql);
		$this->iduser = "NULL"; // to be sure
		$query->execute($this->data);
	}

	function update(){
		$sql  = "UPDATE user SET";
		$sql .= " idbooster = :idbooster, name = :name, surname = :surname, password = :password, admin = :admin, role = :role, join_date = :join_date, leave_date = :leave_date, active = :active, comment = :comment, idpromo = :idpromo";
		$sql .= " WHERE iduser = :iduser";

		$conn = mysql::$conn;
		$query=$conn->prepare($sql);
		$query->execute($this->data);
	}

	function delete(){
		$sql = "DELETE FROM user WHERE iduser = :iduser";
		$conn = mysql::$conn;
		$query = $conn->prepare($sql);
		$query->execute(array('iduser' => $this->iduser));
	}

	function __get($attr){
		if(isset($this->data[$attr])){
			return $this->data[$attr];
		}
		else{
			throw new Exception('Unknow attribute '.$attr);
		}
	}

	function __set($attr,$value){
		if(isset($this->data[$attr])){
			$this->data[$attr] = $value;
		}
		else{
			throw new Exception('Unknow attribute '.$attr);
		}
	}
}
?>